package com.me.study.javaBasic;

import org.junit.Test;

import java.util.Random;

public class RetryTest {

    private static final int MAX_TIMES = 2;

    /**
     * 重试方法
     */
    @Test
    public void retry() {
        String result = null;
        int times = 1;
        while (true) {
            try {
                if (new Random().nextInt(4) < 2) {
                    System.out.println("假装处理啥，还成功了。。");
                    result = "success";
                    break;
                } else {
                    throw new RuntimeException("处理失败");
                }
            } catch (Exception e) {
                System.err.println("假装处理啥失败了。重试" + times);

                if(times >= MAX_TIMES) {
                    throw new RuntimeException("重试两次都失败了。", e);
                }
                times++;
            }
        }

        System.out.println(result);
    }

    @Test
    public void retry2() {
        String result = null;
        for (int times = 1; times <= MAX_TIMES; times++) {
            try {
                if (new Random().nextInt(4) < 2) {
                    System.out.println("假装处理啥，还成功了。。");
                    result = "success";
                    break;
                } else {
                    throw new RuntimeException("处理失败");
                }
            } catch (Exception e) {
                System.err.println("假装处理啥失败了。重试" + times);
                result = e.getMessage();
            }

        }

        System.out.println(result);
    }

    /**
     * 循环代码块，do...whild 必定执行一次
     */
    @Test
    public void loop() {
        int pageNo = 1;
        int pageCount = 0;// 总页数

        do {
            if (new Random().nextBoolean()) {
                throw new RuntimeException("循环过程失败");
            } else {
                System.out.println("循环-" + pageNo);
            }

            // 如果是查询第一页数据，获取总页数
            if (pageNo == 1) {
                pageCount = 2;
            }
            pageNo++;
        } while (pageNo <= pageCount);

    }

}
